<template>
  <div class="book-management-container">
    <!-- 顶部标题和操作区 -->
    <div class="header-section">
      <div class="title-section">
        <h2 class="page-title">
          <i class="el-icon-notebook-2"></i>
          图书管理系统
        </h2>
        <div class="action-area">
          <el-input
            placeholder="输入图书名称/ISBN搜索"
            v-model="searchKey"
            class="search-input"
            clearable
            @clear="getList"
            @keyup.enter.native="getList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
              class="search-btn"
            ></el-button>
          </el-input>
          <el-button 
            @click="addBook" 
            type="primary" 
            icon="el-icon-plus"
            class="add-btn"
          >
            新增图书
          </el-button>
        </div>
      </div>
    </div>

    <!-- 图书表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        class="book-table"
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column
          label="序号"
          width="80"
          align="center"
        >
          <template slot-scope="scope">
            <span class="index-number">{{ (cp - 1) * 15 + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="product_name"
          label="图书名称"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <span class="book-name">{{ scope.row.product_name }}</span>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="category_name"
          label="图书分类"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.category_name }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="product_title"
          label="副标题"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <span class="book-subtitle">{{ scope.row.product_title }}</span>
          </template>
        </el-table-column>
        
        <el-table-column
          label="图书简介"
          width="220"
        >
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              width="300"
              trigger="hover"
              :content="scope.row.product_intro"
            >
              <div slot="reference" class="book-intro">
                {{ scope.row.product_intro.slice(0, 25) + '...' }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        
        <el-table-column
          label="封面"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 60px; height: 80px"
              :src="'http://localhost:3000/' + scope.row.product_picture"
              fit="contain"
              :preview-src-list="['http://localhost:3000/' + scope.row.product_picture]"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        
        <el-table-column
          label="价格"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <div class="price-section">
              <span class="original-price">¥{{ scope.row.product_price }}</span>
              <span class="selling-price">¥{{ scope.row.product_selling_price }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="product_num"
          label="库存"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span :class="{
              'stock-normal': scope.row.product_num > 10,
              'stock-warning': scope.row.product_num <= 10 && scope.row.product_num > 0,
              'stock-danger': scope.row.product_num <= 0
            }">
              {{ scope.row.product_num }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="product_sales"
          label="销量"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span class="sales-count">{{ scope.row.product_sales }}</span>
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="220"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button
                @click.native.prevent="readDetail(scope)"
                type="primary"
                icon="el-icon-view"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="编辑信息" placement="top">
              <el-button
                @click.native.prevent="editor(scope)"
                type="warning"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="下架图书" placement="top">
              <el-button
                @click.native.prevent="_delete(scope)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="上传图片" placement="top">
              <el-button
                @click.native.prevent="uploadImg(scope)"
                type="info"
                icon="el-icon-upload"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        @current-change="changeCP"
        :current-page="cp"
        :page-size="15"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 上传图片对话框 -->
    <el-dialog
      :title="`上传图书图片 - ${currentBookName}`"
      :visible.sync="uploadDialogStatus"
      width="50%"
      class="upload-dialog"
    >
      <div class="upload-content">
        <el-upload
          class="upload-demo"
          action=""
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :file-list="fileList"
          list-type="picture-card"
          :limit="5"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过2MB
          </div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogStatus = false">取 消</el-button>
        <el-button type="primary" @click="uploadDialogStatus = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      cp: 1,
      total: 0,
      uploadDialogStatus: false,
      fileList: [],
      row: {},
      searchKey: '',
      loading: false,
      currentBookName: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    beforeUpload(file) {
      let params = new FormData()
      params.append('file', file)
      params.append('id', this.row.row.product_id)
      this.$axios.post('/api/product/upload', params, {headers: {'Content-Type': 'multipart/form-data'}})
        .then(res => {
          if (res.data.code == '001') {
            this.fileList.push({
              id: res.data.data.id,
              intro: res.data.data.intro,
              product_id: res.data.data.product_id,
              name: res.data.data.product_picture.split('/')[res.data.data.product_picture.split('/').length - 1],
              url: 'http://localhost:3000/'+res.data.data.product_picture,
              status: "success"
            })
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
      return false
    },
    
    handleRemove(file) {
      this.$axios.post('/api/product/deleteProductImg', {
        id: file.id
      })
        .then(res => {
          if (res.data.code == '001') {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    
    uploadImg(row) {
      this.row = row
      this.currentBookName = row.row.product_name
      this.$axios.post('/api/product/getProductImgs', {
        product_id: row.row.product_id
      })
        .then(res => {
          if (res.data.code == '001') {
            this.fileList = res.data.data.map(item => ({
              id: item.id,
              intro: item.intro,
              product_id: item.product_id,
              name: item.product_picture.split('/')[item.product_picture.split('/').length - 1],
              url: 'http://localhost:3000/'+item.product_picture,
              status: "success"
            }))
            this.uploadDialogStatus = true
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    
    getList() {
      this.loading = true
      this.$axios.post('/api/product/getAdminList', {
        cp: this.cp,
        searchKey: this.searchKey
      })
        .then(res => {
          this.tableData = res.data.data.data || []
          this.total = res.data.data.total || 0
        })
        .catch(() => {
          this.$message.error('获取图书列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    changeCP(index) {
      this.cp = index
      this.getList()
    },
    
    _delete(row) {
      this.$confirm('此操作将永久下架该图书及其所有图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post('/api/product/delete', {
          id: row.row.product_id
        })
          .then(res => {
            if (res.data.code == '001') {
              this.$message.success(res.data.msg)
              this.getList()
            } else {
              this.$message.error(res.data.msg)
            }
          })
      }).catch(() => {})
    },
    
    addBook() {
      this.$router.push({
        path: '/addOrEdit',
        query: {
          type: 'add'
        }
      })
    },
    
    editor(row) {
      this.$router.push({
        path: '/addOrEdit',
        query: {
          type: 'edit',
          id: row.row.product_id
        }
      })
    },
    
    readDetail(row) {
      this.$router.push({
        path: '/addOrEdit',
        query: {
          type: 'detail',
          id: row.row.product_id
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.book-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header-section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  
  .title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .page-title {
      margin: 0;
      font-size: 18px;
      color: #333;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 10px;
        font-size: 20px;
        color: #409EFF;
      }
    }
    
    .action-area {
      display: flex;
      align-items: center;
      
      .search-input {
        width: 300px;
        margin-right: 15px;
        
        ::v-deep .el-input__inner {
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
      }
      
      .search-btn {
        background-color: #409EFF;
        color: white;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        
        &:hover {
          background-color: #66b1ff;
        }
      }
      
      .add-btn {
        padding: 10px 15px;
      }
    }
  }
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
  
  .book-table {
    border-radius: 4px;
    overflow: hidden;
    
    ::v-deep th {
      background-color: #f8f8f9 !important;
      font-weight: 600;
      color: #515a6e;
    }
    
    .index-number {
      color: #909399;
    }
    
    .book-name {
      font-weight: 500;
      color: #333;
    }
    
    .book-subtitle {
      color: #666;
      font-size: 13px;
    }
    
    .book-intro {
      color: #999;
      cursor: pointer;
      font-size: 13px;
      line-height: 1.5;
      
      &:hover {
        color: #409EFF;
      }
    }
    
    .price-section {
      display: flex;
      flex-direction: column;
      
      .original-price {
        text-decoration: line-through;
        color: #999;
        font-size: 12px;
      }
      
      .selling-price {
        color: #f56c6c;
        font-weight: 500;
      }
    }
    
    .stock-normal {
      color: #67C23A;
    }
    
    .stock-warning {
      color: #E6A23C;
    }
    
    .stock-danger {
      color: #F56C6C;
    }
    
    .sales-count {
      color: #409EFF;
    }
  }
}

.pagination-container {
  text-align: right;
  padding: 10px 0;
}

.upload-dialog {
  .upload-content {
    padding: 20px;
    
    ::v-deep .el-upload {
      width: 100px;
      height: 140px;
      line-height: 140px;
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
      
      &:hover {
        border-color: #409EFF;
      }
    }
    
    .el-upload__tip {
      margin-top: 10px;
      color: #999;
      font-size: 12px;
    }
  }
  
  .dialog-footer {
    .el-button {
      padding: 10px 20px;
    }
  }
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 24px;
}
</style>